package com.star.warmwinter.http;

import android.util.Log;

import com.star.warmwinter.App;
import com.star.warmwinter.http.config.HttpConfig;
import com.star.warmwinter.http.config.InterceptorUtils;

import java.io.File;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: blackbai11
 * Date: 2017/7/19 16:31
 * Description: 网络请求 client
 */

public class RetrofitClient {
    private static String TAG = "RetrofitClient";

    // retrofit实例
    private Retrofit mRetrofit;

    /**
     * 私有化构造方法
     */
    private RetrofitClient() {
        // 创建一个OkHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        //设置缓存目录
        File cacheFile = new File(App.getInstance().getExternalCacheDir(), HttpConfig.CACHE_NAME);
        Cache cache = new Cache(cacheFile, HttpConfig.CACHE_SIZE);                  //生成缓存，50M

        builder.readTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)           //设置超时
                .writeTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)                                     // 失败后尝试重新请求
                .addNetworkInterceptor(InterceptorUtils.httpLoggingInterceptor())   //设置 Debug Log 模式
                .cache(cache).addInterceptor(InterceptorUtils.cacheInterceptor());  //缓存策略
//                .addInterceptor(InterceptorUtils.addQueryParameterInterceptor())  //公共参数
//                .addInterceptor(InterceptorUtils.headerInterceptor())             //设置头
        OkHttpClient okHttpClient = builder.build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(HttpConfig.BASE_URL)
                .client(okHttpClient)
//                .addConverterFactory(ScalarsConverterFactory.create())//  compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 调用单例对象
     */
    private static RetrofitClient getInstance() {
        return HttpClientInstance.instance;
    }

    /**
     * 创建单例对象
     */
    private static class HttpClientInstance {
        static RetrofitClient instance = new RetrofitClient();
    }

    ///////////////////////////////////////////////////////////////////////////
    // service
    ///////////////////////////////////////////////////////////////////////////
    private static TreeMap<String, Object> serviceMap;

    private static TreeMap<String, Object> getServiceMap() {
        if (serviceMap == null)
            serviceMap = new TreeMap<>();
        return serviceMap;
    }

    /**
     * @return 指定service实例
     */
    public static <T> T getService(Class<T> clazz) {
        if (getServiceMap().containsKey(clazz.getSimpleName())) {
            return (T) getServiceMap().get(clazz.getSimpleName());
        }

        Log.d(TAG, "need to create a new " + clazz.getSimpleName());
        T service = RetrofitClient.getInstance().mRetrofit.create(clazz);
        getServiceMap().put(clazz.getSimpleName(), service);
        return service;
    }
}
